const express = require('express')
const router = express.Router()
const mysql = require("../mysql/config")
let connection = null
const resSend = require('../utils/resSend')

router.post("/add", (req, res) => {
    connection = mysql.createConnection()
    connection.connect()
    let params = [req.body.couponId, req.user.id]
    connection.query(`SELECT * FROM useryhq_table WHERE couponId=? AND status=0`, req.body.couponId, (err, result1) => {
        if (err) {
            resSend(res, 500, "服务异常！")
        } else {
            if (result1.length > 0) {
                resSend(res, 500, "已经领取过了！")
            } else {
                // 添加优惠券
                connection.query(`INSERT INTO useryhq_table (couponId,userId) VALUES (?,?)`, params, (err, result) => {
                    if (err) {
                        resSend(res, 500, "服务异常！")
                    } else {
                        connection.query("UPDATE coupon_table SET allCount=? WHERE id=?", [req.body.allCount - 1, req.body.couponId], (error, results) => {
                            if (error) {
                                resSend(res, 500, "服务异常！")
                            } else {
                                resSend(res, 200, '操作成功！')
                            }
                        })
                    }
                })
            }
        }
    })
})

// 获取用户优惠券
router.get("/getyhq", (req, res) => {
    connection = mysql.createConnection()
    connection.connect()
    let params = [req.user.id,req.query.status?Number(req.query.status)?1:0:0]
    console.log(params);
    connection.query(`SELECT * FROM useryhq_table WHERE userId=? AND status=?`, params, (err, result) => {
        if (err) {
            resSend(res, 500, "服务异常！")
        } else {
            if (result.length > 0) {
                result.forEach(val => {
                    connection.query(`SELECT * FROM coupon_table WHERE id=?`, [val.couponId], (err, result) => {
                        if (err) {
                            resSend(res, 500, "服务异常！")
                        } else {
                            val.conDetails = result[0]
                        }
                    })
                });
            }
            setTimeout(() => {
                resSend(res, 200, "操作成功！", result)
            }, 500)
        }
    })
})

// 修改优惠券状态
router.post("/update", (req, res) => {
    connection = mysql.createConnection()
    connection.connect()
    let params = [req.body.id]
    // 修改优惠券
    connection.query(`UPDATE useryhq_table SET status=1 WHERE id=?`, params, (err, result) => {
        if (err) {
            resSend(res, 500, "服务异常！")
        } else {
            resSend(res, 200, '操作成功！')
        }
    })
})

module.exports = router